# pylint: disable-msg=E1101
"""
@author: Sergiy Tsymbalyuk
"""

import logging

from pylons import tmpl_context as c, request
from pylons.i18n import lazy_ugettext as _

from sqlalchemy.sql import or_

from repoze.what.plugins.pylonshq import ActionProtector
from repoze.what.predicates import has_permission

from hrms.lib.base import BaseController, render, Session
from hrms.model.person import Employee

from chowa.model.organization import *
from chowa.lib.site.navigation import get_page

log = logging.getLogger(__name__)

class OrganizationController(BaseController):
    @ActionProtector(has_permission('site.administer.organization'))
    def districts(self):
        query = Session.query(District)
        c.districts = query.all()
        return render('/hrms/organization/districts.html')
    
    @ActionProtector(has_permission('site.administer.organization'))
    def division(self, id):
        query = Session.query(Employee)
        query = query.join(Division)
        query = query.filter(Division.id == id)
        
        c.employees = query.all()
        c.division = Session.query(Division).get(id)
        return render('/hrms/organization/division.html')
    
    def structure(self):
        district_query = Session.query(District)
        c.main_district = district_query.filter_by(is_primary=True).one()
        
        query = Session.query(Division) \
            .join(DivisionType) \
            .filter(Division.is_disabled == False)
        c.subdivisions = lambda superior: query \
            .join(Subordination, Division.id == Subordination.division_id) \
            .filter(Subordination.superior_id == superior.id).all()
        c.divisions = lambda district, manage: query \
            .filter(Division.district == district) \
            .filter(DivisionType.must_subordinate == manage).all()
        
        c.districts = district_query.filter_by(is_primary=False).all()
        return render('/hrms/organization/structure.html')
    
    def search(self):
        c.name = request.params.get('name')
        c.district = request.params.get('district')
        query = Session.query(Employee)
        if c.name:
            query = query.filter(or_(Employee.surname.like('%%%s%%' % c.name),
                                     Employee.name.like('%%%s%%' % c.name),
                                     Employee.patronymic.like('%%%s%%' % c.name)))
        if c.district:
            query = query.join(Division).filter(Division.district_id == c.district)
        c.employees = get_page(query, items_per_page=20)
        return render('/hrms/organization/search.html')
